<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 */
class Hongniu2Controller extends PayController{
    protected $config;
    protected $class;
    private $private = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDX5rWXhaj5FAq3Hfv6B6HoqMusBzUfBXIbYMCm/SN8Q6brLlrc2Ivnl2dq53MnzQE+FnoRdQNwcuKxUvxi0tK7GZdfOK0SdKrqxKwz0kr/UuFEW6Zb1AlrLyMSxQa6b5Uvu9OzR8viOxd/2bfTEuVKLI93lizAfgoCHFaYmBExE/XbL6gFSNz8JTEi36skV6JPGX8ymXrra+RBF/cOUZifQXZYJdlJxVSURA6vC/qSg2iek1E42d0FrXoj8nL3ciXCjDmV6rQYBajf3f6YEyXPIWxG8CnxeAhtKmXKCIW8qTBWVjl5N69awuAB2OnM+Za7GDMo5lphlBc03TYfcxr1AgMBAAECggEABhXWoHXmYVh5qz4JHO8CI6o+TPowoRzO+1gqySO+NrTUpTEiFn90BT8ObZDzsF3mEkRUt6rYqF67ADLnZWtHAHo9x5oaJrieTw4XQtt2ibCVJA9ODRO/TQOzG8a55Dj1t4OC+aNyBIDHey8KMCs9xm1v514wPLmD7Rm0LYp7t/coaDa+eZrEiafjUEyUaqsBFQ3rltn/epK9UkFNYpENNtA1OTxWuqsu/xLQOa+xJVh/9JoqLASzyu53dyuDXmiz6nC8zaL5ZAm66EZ/oLm4txPiQybUm1P4rUNEkO4icVCMGHKxf5H9b/vpyt/GB1sm7BApqJlI8P1GWS49aQAHMQKBgQDuLXwq2oo13OSpJRwxQi3kB74waSXwPh6ZAvZ/RU/E4J4NdFy45ZDgP8etUCgIl44coOHMnU+7mp24yMsaGU3ZCgU8/pzRpA0/8cqFdG0TikgoJXxsYHD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zyFsRvAp8XgIbSplygiFvKkwVlY5eTevWsLgAdjpzPmWuxgzKOZaYZQXNN02H3Ma9QIDAQAB";
    private $web_public = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAy+feqgQQb17xuUXofHp8nALYoVW06oneWRBfh532s4zwmFN2VHFO+cymD6Alo32jfhIW3+a+X/W4tThzEWG9dgR2kdudW2RZc5fIo0h+37rNKuF30Rz5NTY0tfG4zLPEsfr3vosBP6nHUPbKpc0dxp0vlkuvlpkTRk6yr5vsjwRW8M7nla5THgel/iBV1b98iiN2WqG2esDDVm6Jjb3wXjZZcr1gykya1ngtAkKGdUP0M8IOF90WkNaaBxkfEUBfGHJD+8cdQ+MAMYrOtMK7ZI4oqWpVghPMmHMDDNXZ1M/4LQ/lPPrvIXSL1/7jM9KpNAkIvWpLphtasi0W8Iv3XwIDAQAB";

    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['brandNo'] = $this->config['mch_id'];
        $data['orderNo'] = $return['orderid'];
        $data['price'] = number_format($return['amount'],2,'.','');
        switch($this->config['paytype']){
            case 1:
                $data['serviceType'] = '1102';
                break;
            case 2:
                $data['serviceType'] = '1202';
                break;
            //银联扫码
            case 11:
                $data['serviceType'] = '1105';
                break;
                //银联快捷
            case 13:
                $data['serviceType'] = '1003';
                break;
            //支付宝H5
            case 3:
            case 4:
            case 17:
            case 18:
                //$data['serviceType'] = '1101';
                $data['serviceType'] = '1201';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['userName'] = 'hongniu';
        $data['clientIP'] = getIP();

        ksort($data);
        $str = httpstr($data);

        $merchant_private_key = "-----BEGIN PRIVATE KEY-----"."\r\n".wordwrap(trim($this->private),64,"\r\n",true)."\r\n"."-----END PRIVATE KEY-----";
        $merchant_private_key = openssl_get_privatekey($merchant_private_key);
        openssl_sign($str, $sign_info, $merchant_private_key, OPENSSL_ALGO_MD5);
        $signature = base64_encode($sign_info);

        $data['signature'] = $signature;
        $data['callbackUrl'] = $return['notifyurl'];
        $data['frontUrl'] = $return['callbackurl'];
        $data['signType'] = 'RSA-S';

        $params = json_encode($data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->config['gateway']);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: '.strlen($params)));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);

        $res = curl_exec($ch);

        $res = json_decode($res, true);

        //echo "<pre/>"; print_r($res);exit;

        $code = $res['data']['payUrl'];

        if(!$code){
            if($res['message']){
                $this->showmessage($res['message'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $paytype = transArr( C("PAYTYPES"), "id");

        //$this->assign("wap_url", $code);
        //$this->assign("code_url", $code);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            case 3:
            case 4:
            case 17:
            case 18:
                if(isMobile()){
                    header("location: {$code}");
                }else{
                    header("location: {$code}"); exit;
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                header("location: {$code}");
        }
    }

    private function rsaCheck($data, $public_key, $sign)  {
        $search = [
            "-----BEGIN PUBLIC KEY-----",
            "-----END PUBLIC KEY-----",
            "\n",
            "\r",
            "\r\n"
        ];
        $public_key=str_replace($search,"",$public_key);
        $public_key=$search[0] . PHP_EOL . wordwrap($public_key, 64, "\n", true) . PHP_EOL . $search[1];
        $res=openssl_get_publickey($public_key);
        if($res)
        {
            $result = (bool)openssl_verify($data, base64_decode($sign), $res, MD5);
            openssl_free_key($res);
        }else{
            exit("公钥格式有误!");
        }
        return $result;
    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();

        $arr = [
            '40.115.179.121',
            '23.100.103.148',
            '23.100.98.124',
            '23.100.99.162',
            '23.100.100.216',
            '23.100.97.34',
            '23.100.102.146',
            '23.100.102.43',
            '52.79.180.28',
            '40.83.103.23',
        ];
        if(!$this->checkip(getIP(), $arr)){
            exit("wrong");
        }

        $p = file_get_contents('php://input');

        //$p = '{"actualPrice":"49.20","ciphertext":null,"code":0,"dealTime":"2019-06-26 15:40:49.577","message":"","orderNo":"sn20190626153933781","orderStatus":1,"orderTime":"2019-06-26 15:39:35.377","price":"50.00","signature":"rL4REgV6cIim3RNGg9oH78Mdw0lTw27nmrtMwMllsY0rJ%2BhZRrCkym48zvheD4dcCmhPBITow4ZMLwPZzkwWNOKEmcTCs9ANQrbpYKSRTWsVHoeJjjE41OOKPqqDViB7FIpPaberCHGcnwHTa0XzlR62Rrb19HxiWLINy61JPV%2BfEdXFS3%2BwnAHW%2F6ne2HLNnSigZx%2B1kERFHwfJN3zD2XMF%2B2OS9%2BmuirYFFmfSsoLFaWBr%2FEmCJ%2BF%2FKO%2FtqQAE2CBM0rmpEtyzxn4nusIWi2crRWqtPwehXPiXi%2FpoZn%2FGdTG%2BRZ8XGvalHbXWn%2FjHnzbGN3URpz3V4UhzHAg47Q%3D%3D","tradeNo":"1906260000018164"}';

        if(!$p){
            exit("no_data");
        }

        $p = $back_data =json_decode($p, true);

        $signStr = "actualPrice=".$back_data['actualPrice']."&dealTime=".date("YmdHis",strtotime($back_data['dealTime']))."&orderNo=".$back_data['orderNo']."&orderStatus=".$back_data['orderStatus']."&orderTime=".date("YmdHis",strtotime($back_data['orderTime']))."&price=".$back_data['price']."&tradeNo=".$back_data['tradeNo'];

        $str = $signStr;

        $sign = $back_data['signature'];
        $sign = urldecode($sign);

        $flag = $this->rsaCheck($str,$this->web_public,$sign);

        if(!$flag){
            exit("sign wrong");
        }

        //echo "<pre/>"; print_r($p); exit;

        //获取订单信息
        $orderid = $p['orderNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_true" => $p['actualPrice'],
        ));

        if($p['orderStatus'] !== 1){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'OK');
    }

    public function callBackUrl(){
        echo '处理成功'; exit;
    }

    function getSignStr($Obj){
        foreach ($Obj as $k => $v) {
            if($v != '' && $k != 'sign'){
                $Parameters[$k] = $v;
            }
        }
        ksort($Parameters);
        return urldecode($this->formatBizQueryParaMap($Parameters));
    }

    function formatBizQueryParaMap($paraMap){
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if($v != null && $v != ''){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return urlencode($reqPar);
    }

    function http_poststr($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $return_content;
    }
}